<template>
  <div>
    <el-form :label-position="'left'" label-width="150px">
      <el-form-item label="搜索用户" v-if="!editFlag && admin_info.role==1">
        <el-select
          v-model="executor"
          filterable
          remote
          :loading="loading"
          placeholder="请输入昵称/姓名"
          @change="getExecutor"
          :remote-method="searchName"
          style="width:200px"
          value-key="user_id"
          size="medium"
        >
          <div v-if="vipList.length!=0">
            <el-option
              v-for="(item) in vipList"
              :key="item.user_id"
              :label="item.realname?item.realname:item.nickname"
              :value="item">
              <!-- <template >
                  <div>{{item.realname?item.nickname:item.nickname}}&nbsp;&nbsp;&nbsp; <span @click.stop="showPersodDetail(item.id)" style="cursor:pointer;color:#409EFF">查看详情</span></div>
              </template> -->
            </el-option>
          </div>
        </el-select>
      </el-form-item>
      <el-form-item label="真实姓名">
        <el-input v-model="member.realname" style="width:200px" placeholder="请输入专家真实姓名"></el-input>
      </el-form-item>
      <el-form-item label="头像">

        <el-upload
          class="avatar-uploader"
          action="https://wxapp.gdhrma.org.cn/api/file/upload-img"
          name="photo"
          :show-file-list="false"
          :on-success="handlePhotos"
          :before-upload="beforeAvatarUpload">
          <img v-if="photoImg" :src="photoImg" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="联系方式">
        <el-input v-model="member.phone" style="width:200px" placeholder="请输入专家联系方式"></el-input>
      </el-form-item>
      <el-form-item label="所在单位">
        <el-input v-model="member.company" style="width:300px" placeholder="请输入专家所属单位"></el-input>
      </el-form-item>
      <el-form-item label="城市" prop="origin">
        <el-cascader
          placeholder="选择地址"
          :options="ORIGIN"
          :props="{value:'label'}"
          v-model="member.address"
          class="cascader"
          filterable></el-cascader>
      </el-form-item>
      <el-form-item label="职称">
        <el-input v-model="member.position" style="width:200px" placeholder="请输入专家职称"></el-input>
      </el-form-item>
      <el-form-item label="擅长领域">
        <el-input v-model="member.goodAt" type="textarea" autosize style="width:800px" placeholder="请编辑专家擅长领域"></el-input>
      </el-form-item>
      <el-form-item label="专家标签">
        <el-input v-model="tag" palceholder="输入专家标签" style="width:200px" placeholder="请输入专家标签并点击添加按钮"></el-input>
        <el-button type="primary" @click="addTag">添加</el-button>
      </el-form-item>
      <el-form-item>
        <div class="memberPicWrapper">
          <div class="memberPicDetail" v-for="(item,index) of tagList" :key="index">
            <div>{{item}}</div>
            <img src="../../../static/images/delete.png" alt="" class="delete" @click.stop="deleteTag(item,index)">
          </div>
        </div>
      </el-form-item>
      <el-form-item label="认证状态">
        <el-select v-model="member.auth" placeholder="选择分类">
          <el-option
            v-for="item in authOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资质证明">
        <el-upload
          class="upload-demo"
          action="https://wxapp.gdhrma.org.cn/api/file/upload-img"
          name="photo"
          :on-preview="handlePreview"
          :on-success="handlePhoto"
          :on-remove="handleRemove"
          :file-list="fileList"
          style="width:300px"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model="member.sortNum" style="width:200px" placeholder="数字越小越靠前"></el-input>
      </el-form-item>


      <div class="add-table-wrapper">
        <el-button type="primary" @click="commit" class="add-table-wrapper-btn">保存</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
  import ORIGIN from '../../assets/json/origin.json';

  export default {
    data() {
      return {
        editFlag: false,//判断是新增还是编辑
        ORIGIN,
        id: '',//专家id
        photoImg: '',
        photoId: '',
        intelligenceImg: '',//资质证明
        intelligenceId: '',
        member: {
          realname: '',
          phone: '',
          company: '',
          address: [],
          position: '',
          goodAt: '',
          auth: '',
          sortNum: ''
        },
        fileList: [],
        tag: '',
        tagList: [],
        authOptions: [
          {label: '正常', value: 1},
          {label: '注销', value: 3}

        ],
        myConfig: {
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 初始容器高度
          initialFrameHeight: 500,
          // 初始容器宽度
          initialFrameWidth: '100%',
          // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
          // serverUrl: 'http://35.201.165.105:8000/controller.php',
          serverUrl: 'https://wxapp.gdhrma.org.cn/ueditor-php/controller.php',
          // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
          //UEDITOR_HOME_URL: '/peoples_association_backstage/dist//static/UEditor/'
          toolbars: [
            [
              'undo', 'redo', '|',
              'bold', 'italic', 'underline', 'strikethrough',
              'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor',
              'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
              'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
              'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
              'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
              'simpleupload', 'insertimage', 'insertvideo', 'music',
              'horizontal', 'date', 'time',
              'inserttable'
            ]
          ]
        },
        loading: true,
        vipList: [],
        executor: {},//用户
        admin_info:""
      }
    },
    computed: {
      imgList() {

        return this.fileList.map(item => {
          if (item.response) {
            return item.response.data.id
          } else {
            return item.id
          }

        })
      }
    },
    methods: {
      //获取管理员信息
      async getAdminUserInfo(){
        let params = {
          user_token: window.localStorage.getItem('user_token'),
        }
        const res = await this.$api.getAdminUserInfo(params);
        console.log("res",res)
        if(res.data.level=='success'){
          this.noticeMessageCount = res.data.admin_message;
          this.admin_info = res.data.data;
        }else{

        }
      },
      getExecutor(e) {
        this.executor = e;
        this.member.realname = e.realname ? e.realname : e.nickname;
        this.photoImg = e.photo_url;
        this.photoId = e.photo_id
      },
      async searchName(searchText) {
        //搜索用户名
        this.loading = true;
        let params = {
          page: 1,
          limit: 999,
          keyword: searchText
        }
        let res = await this.$api.getUserList(params);
        if (res.data.level == 'success') {
          let arr = []
          res.data.data.forEach(item => {
            if (item.user_info) {
              arr.push(item.user_info)
            }
          });
          this.vipList = arr
        }
        this.loading = false
      },
      async commit() {
        let params = {
          user_id: this.executor.user_id,
          id: this.id,
          realname: this.member.realname,
          photo_id: this.photoId,
          unit_name: this.member.company,
          position: this.member.position,
          province: this.member.address[0] || '',
          city: this.member.address[1] || '',
          area: this.member.address[2] || '',
          strengths: this.member.goodAt,
          labels: this.tagList,
          qualification_imgs: this.imgList,
          status: this.member.auth,
          sort: this.member.sortNum,
          phone: this.member.phone
        };
        console.log(params);

        let res = await this.$api.setExpert(params);
        if (res.data.level == 'success') {
          this.$message.success(res.data.message);
          this.$router.go(-1)
        } else {
          this.$message.error(res.data.message)
        }
      },
      beforeAvatarUpload(file) {
        //上传照片前的操作
        // console.log(file,555)
      },
      handlePhotos(res, file) {
        //上传照片成功
        if (res.data) {
          this.photoImg = res.data.img_url;
          this.photoId = res.data.id;
        }
      },
      handlePreview(file) {
        console.log(file);
      },
      handleRemove(file, fileList) {
        //移除资质照片
        this.fileList = fileList
      },
      handlePhoto(res, file, fileList) {
        //上传资质照片成功
        this.fileList = fileList.map(item => {
          let obj = {};
          obj.id = item.response.data.id;
          obj.url = item.response.data.img_url;
          return obj
        })
        this.fileList = fileList
      },
      addTag() {
        if (this.tag == '') {
          this.$message({
            type: 'warning',
            message: '标签不能为空'
          });
          return;

        }
        this.tagList.push(this.tag);
        this.tag = ''
      },
      deleteTag(item, index) {
        //删除电子资料
        this.tagList.splice(index, 1);
      },
      async getExpertDetail(id) {
        //显示详情信息
        let res = await this.$api.getExpertDetail({id: id})
        if (res.data.level == 'success') {
          let data = res.data.data;
          this.photoId = data.photo_id;
          this.photoImg = data.photo_url;
          this.fileList = data.expert_qualification_img.map(item => {
            return {
              id: item.img_id,
              url: item.img_url
            }
          })

          this.member.phone = data.phone;
          this.member.company = data.unit_name;
          this.member.position = data.position;
          this.member.goodAt = data.strengths;
          this.tagList = data.expert_label;
          this.member.auth = +data.is_auth;
          this.member.sortNum = data.sort;
          this.member.address = [data.province, data.city, data.area]
          this.member.realname = data.realname ? data.realname : data.nickname
          this.vipList = [{realname: data.realname, nickname: data.nickname, user_id: data.user_id}]

        } else {
          this.$message.error(res.data.message)
        }
      },
    },
    mounted() {
      this.id = this.$route.query.id;
      if (this.id) {
        this.editFlag = true
        this.getExpertDetail(this.id)
      }

      this.getAdminUserInfo();
    },
  }
</script>
<style lang="scss" scoped>
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: contain;
  }

  .add-table-wrapper {
    display: flex;
    justify-content: center;
    padding: 30px 0;
  }

  .memberPicWrapper {
    display: flex;
    flex-wrap: wrap;
  }

  .memberPicDetail {
    text-align: center;
    margin: 0 10px;
    position: relative;

    .delete {
      width: 20px;
      height: 20px;
      position: absolute;
      top: -10px;
      right: -10px;
    }
  }
</style>
